package drds.configuration.db.transaction;

import drds.configuration.db.JdbcUtil;
import drds.configuration.db.datasource.DataSourceContext;
import drds.configuration.db.datasource.DataSourceIdToDataSourceConfigMapContext;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
public class Transaction {
    /**
     * 获取事务中的数据库连接
     *
     * @param dataSourceId 每个地方都会有这个的
     */
    public static Connection getConnectionFromTransactionContextIfTransactioning(String dataSourceId) throws SQLException {
        /**
         * 判断是否处于事务中 如果是则从事务里面获取
         */

        if (TransactionContext.isTransactioning()) {
            /**
             * 对比当前组数据源ID是否一致
             */
            if (!dataSourceId.equals(TransactionContext.getDataSourceId())) {
                throw new RuntimeException("dataSourceId is not equals");
            }
            return TransactionContext.getConnection();
        } else {
            DataSourceContext dataSourceContext = DataSourceIdToDataSourceConfigMapContext.dataSourceIdToDataSourceConfigMap.get(dataSourceId);
            if (dataSourceContext == null) {
                throw new NullPointerException("dataSourceContext");
            }
            return dataSourceContext.getDataSource().getConnection();
        }
    }

    public static void close(Connection connection) {
        if (TransactionContext.isTransactioning()) {
            //
        } else {
            JdbcUtil.close(connection);
        }
    }

}
